<template>
  <div>
    <a-card class="card-header">
      <a-form-model ref="ruleForm" :model="model" :rules="rules">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="商品编号"
              hasFeedback
            >
              <a-input disabled v-model.trim="model.goodsCode" />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="商品名称"
              hasFeedback
            >
              <a-input disabled v-model.trim="model.goodsName" />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="商品规格"
              hasFeedback
            >
              <a-input disabled v-model.trim="model.specifications" />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="商品类型"
              hasFeedback
            >
              <a-input disabled v-model.trim="model.goodsTypeName" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- line-2 -->
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="来源"
              hasFeedback
            >
              <a-select
                disabled
                v-model.trim="model.source"
                placeholder="请选择来源"
                @search="handleSearch"
              >
                <a-select-option
                  v-for="item in sourceOption"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.dictName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="数量"
              hasFeedback
            >
              <a-input-number
                style="width:100%"
                :min="0"
                :disabled="model.level === 1 ? true : false"
                placeholder="请输入商品数量"
                onkeypress="return event.charCode >= 48"
                v-model.trim="model.quantity"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注"
              hasFeedback
            >
              <a-input placeholder="请输入备注" v-model.trim="model.remark" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <a-card class="card-content" v-if="isShow">
      <!-- 表格区域 -->
      <a-row :gutter="24">
        <a-col>
          <div class="flex flex-a-c">
            <span class="work-title">工序详情</span>
            <a-button type="primary" @click="handleworkAdd">添加工序</a-button>
            <!-- <a-button
              type="primary"
              @click="
                handleworkExport(
                  '工序列表',
                  model.bomWorkStageList,
                  excelColumns
                )
              "
              >导出</a-button
            >
            <a-button
              type="primary"
              @click="handelExportTemplate('工序列表模板', excelColumns)"
              >导出模板</a-button
            > -->
            <!-- <a-button type="primary" @click="handelImport">导入</a-button> -->
            <input
              type="file"
              id="fileTemp"
              ref="fileTemp"
              v-show="false"
              accept=".xls, .xlsx, .excel"
              @input="getImportFile"
            />
          </div>
        </a-col>
      </a-row>
      <br />
      <a-table
        :columns="columns"
        :filterMultiple="false"
        :data-source="model.bomWorkStageList"
        :pagination="false"
        @change="handleTableChange"
        bordered
        :rowKey="(record, index) => record.id"
      >
        <template slot="action" slot-scope="text, record, index">
          <a @click="moveUp(record, index)">上移一行</a>
          <a-divider v-hasPromise="'productDetail'" type="vertical" />
          <a @click="moveDown(record, index)">下移一行</a>
          <a-divider v-hasPromise="'productDetail'" type="vertical" />
          <a @click="handleworkEdit(record, index)">编辑</a>
          <a-divider v-hasPromise="'productDetail'" type="vertical" />
          <a-popconfirm
            okText="确定"
            cancelText="取消"
            v-if="model.bomWorkStageList.length"
            title="确定删除吗?"
            @confirm="() => handleDelete(index)"
          >
            <a>删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>

    <div class=" footer-btn">
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>

    <WorkModal ref="work" @setData="setData"></WorkModal>
  </div>
</template>

<script>
import { columns, excelColumns } from "./components/tableConfig";
import { tableMinxins } from "@/unit/mixins/tableMinxins.js";
import api from "@/api/apiServer";
import excel from "@/unit/lib/excel";
import WorkModal from "./components/WorkModal.vue";

export default {
  components: { WorkModal },
  mixins: [tableMinxins],
  data() {
    return {
      columns,
      excelColumns,
      isShow: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
      sourceOption: [], // 数据来源
      goodsOption: [],
      Option: [],
      tableData: [],
      disabled: true, // 当前是否可输入
      model: {
        bomWorkStageList: [], // 工序数据源
      },
      list: [],
      current: 0,
      tableOption: [],
      selectedRowKeys: [],
      selectedRowIndex: "",
    };
  },
  computed: {
    rules() {
      return {
        quantity: [
          { required: true, message: "请输入商品数量", trigger: "change" },
        ],
      };
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  mounted() {
    this.productGet(this.$route.query.id);
  },
  methods: {
    // 查询当前详情参数
    async productGet(id) {
      let that = this;
      const res = await api.ProductGet({ id });
      this.model = res.data;
      this.getDictFindByCode(res.data.source);
      if (this.model.bomWorkStageList === null) {
        this.model.bomWorkStageList = [];
      }
    },
    // 数据来源查询
    handleSearch(goodsName) {
      this.getGoodList(goodsName);
    },
    // 获取数据来源
    async getDictFindByCode(source) {
      let parentCode = "dict.source";
      const res = await api.DictFindByCode({ parentCode });
      this.sourceOption = res.data;
      this.sourceOption.forEach((item) => {
        if (item.id === source) {
          if (item.dictName === "自产") {
            this.isShow = true;
          } else {
            this.isShow = false;
          }
        }
      });
    },
    // 查询商品列表
    async getGoodList(goodsName) {
      let params = { pageNumber: 1, pageSize: 10 };
      if (goodsName) {
        params.goodsName = goodsName;
        const res = await api.CommodityList(params);
        this.goodsOption = res.data.data;
      }
    },
    // 工序新增
    handleworkAdd() {
      this.$refs.work.title = "新增";
      this.$refs.work.modalAdd();
    },
    // 工序编辑
    handleworkEdit(record, index) {
      this.current = index;
      this.$refs.work.title = "编辑";
      this.$refs.work.modalEdit(record);
      this.getOption();
    },
    // 获取所有设备数据
    async getOption() {
      let params = { pageNumber: 1, pageSize: 9999, deleteFlag: "N" };
      const res = await api.equipmentListPage(params);
      this.tableOption = res.data.data;
      this.$refs.work.tableOption = res.data.data;
    },
    setData(obj, totalCapacity, title) {
      let { bomWorkStageList } = this.model;
      if (title == "编辑") {
        this.$set(bomWorkStageList, this.current, obj);
        bomWorkStageList[this.current].totalCapacity = totalCapacity;
      } else {
        this.$set(obj, "sort", bomWorkStageList.length);
        bomWorkStageList.push(obj);
        bomWorkStageList[
          bomWorkStageList.length - 1
        ].totalCapacity = totalCapacity;
      }
    },
    // 删除
    handleDelete(index) {
      this.model.bomWorkStageList.splice(index, 1);
    },
    uniqueFunc(arr, uniId) {
      const res = new Map();
      return arr.filter(
        (item) => !res.has(item[uniId]) && res.set(item[uniId], 1)
      );
    },
    // 保存接口
    async submitVulFun() {
      let arr = this.uniqueFunc(this.model.bomWorkStageList, "workStageId");
      if (arr.length !== this.model.bomWorkStageList.length) {
        this.$message.error("工序序号重复，请重新添加");
      } else {
        const res = await api.ProductAddOrUpdate(this.model);
        if (res.code && res.code !== 200) {
          this.$message.error(res.message);
          this.confirmLoading = false;
          return;
        }
        this.$message.success(res.message);
      }
    },
    // 保存
    handleSubmit() {
      const that = this;
      this.model.bomWorkStageList.forEach((item) => {
        return (item.equipNames = undefined);
      });

      // 触发表单验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.submitVulFun();
        } else {
          return false;
        }
      });
    },
    // 导入
    async setImport(list) {
      let newArr = this.model.bomWorkStageList.concat(list);
      this.model.bomWorkStageList = JSON.parse(JSON.stringify(newArr));
    },
    // 导出工序
    handleworkExport(filename, data, columns) {
      let title = [];
      let key = [];
      columns.forEach((item) => {
        if (item.dataIndex !== "action" && item.dataIndex !== "index") {
          title.push(item.title);
          key.push(item.dataIndex);
        }
      });
      data.forEach((item) => {
        if (Array.isArray(item.equipIds)) {
          item.equipIds = item.equipIds.toString();
        }
      });
      const params = {
        title,
        key,
        data,
        autoWidth: true,
        filename,
      };
      excel.export_array_to_excel(params);
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log("selectedRowKeys changed: ", selectedRows[0].sort);
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRowIndex = selectedRows[0].sort;
    },
    //上移
    moveUp(record, index) {
      // console.log(this.model.bomWorkStageList, "13213");
      console.log(index);
      this.upData(this.model.bomWorkStageList, index);
      console.log("上移");
    },
    moveDown(record, index) {
      console.log(index);
      console.log("下移");
      this.downData(this.model.bomWorkStageList,index);
    },
    //上移方法
    upData(fieldData, index) {
      if (index != 0) {
        fieldData[index] = fieldData.splice(index - 1, 1, fieldData[index])[0];
        for (const i in fieldData) {
          fieldData[i].sort = i;
        }
        console.log(fieldData, "io");
      } else {
        fieldData.push(fieldData.shift());
      }
    },
    //下移方法
    downData(fieldData, index) {
      if (index != fieldData.length - 1) {
        fieldData[index] = fieldData.splice(index + 1, 1, fieldData[index])[0];
        for (const i in fieldData) {
          fieldData[i].sort = i;
        }
        console.log(fieldData, "ii");
      } else {
        fieldData.unshift(fieldData.splice(index, 1)[0]);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.card-header {
  margin: 20px 0;
}
.card-title {
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #1e1e1e;
  margin-bottom: 20px;
}
.card-content {
  button {
    margin-right: 20px;
  }
}
.bomFrom {
  margin: 0 20px;
  padding: 30px 60px 20px 60px;
  border: 1px solid #ebedf0;
  border-radius: 2px;
}
.work-title {
  font-size: 16px;
  font-weight: 600;
  color: #1a5eff;
  margin-right: 21px;
}
.footer-btn {
  width: 100%;
  text-align: center;
  margin: 37px 0;
  button {
    width: 200px;
    height: 40px;
    background: #1a5eff;
    border-radius: 2px;
  }
}
</style>
